package com.company.netty.demo.NIO.bufferDemo;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * Scattering: 将数据写入到buffer时，可以采用buffer数组，依次写入（分散）
 * Gathering: 从buffer读数据时，可以采用buffer数组，依次读
 *
 * 如果一次性发送超过8个字符怎么处理
 * */

public class ScatteringAndGatheringDemo {

    public static void main(String[] args) throws IOException {

        //ServerSocketChannel 和 SocketChannel

        /**
         * 创建serverSocketChannel
         * */

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);

        //绑定端口到socket，并启动
        serverSocketChannel.socket().bind(inetSocketAddress);

        //创建buffer数组
        ByteBuffer[] byteBuffers = new ByteBuffer[4];
        byteBuffers[0] = ByteBuffer.allocate(3);
        byteBuffers[1] = ByteBuffer.allocate(5);
        byteBuffers[2] = ByteBuffer.allocate(5);
        byteBuffers[3] = ByteBuffer.allocate(5);

        //等待客户端连接（telnet）
        SocketChannel accept = serverSocketChannel.accept();

        int messageLength = 18;

        while (accept.isConnected()) {
            int byteRead = 0;

            while (byteRead < messageLength) {
                long read = accept.read(byteBuffers);
                byteRead += (int) read; //累计读取的字节数

                System.out.println("byteRead: " + byteRead);

                for (ByteBuffer byteBuffer : byteBuffers) {
                    System.out.println("read:  position: " + byteBuffer.position()+", limit: " + byteBuffer.limit());
                }

            }

            Arrays.asList(byteBuffers).forEach(Buffer::flip);

            long byteWritten = 0;

            while (byteWritten < messageLength) {
                long written = accept.write(byteBuffers);
                byteWritten += written;
                System.out.println("written: " + written);
            }

            Arrays.asList(byteBuffers).forEach(Buffer::clear);


        }



    }

}
